<?php

namespace app\admin\controller;

use app\admin\model\ReasonModel;
use cmf\controller\AdminBaseController;
use think\Controller;
use think\Db;
use think\db\Query;
use think\Request;

class ReasonController extends AdminBaseController
{
    public function index()
    {
        $name=$this->request->param('name');
        $data=Db::name('reason')
            ->where(function (Query $query) use ($name){
               if ($name){
                   $query->where('name','like',"%$name%");
               }
            })
            ->order('id desc')
            ->paginate(2,false,['query'=>$this->request->param()]);
        $page=$data->render();
        return $this->fetch('index',['page'=>$page,'reason'=>$data]);
    }
    public function add()
    {
        return $this->fetch();
    }
    public function addPost()
    {
        $data=input();
        if (empty($data['name'])){
            $this->error('原因不能为空');
        }
        $add=ReasonModel::create($data);
        if ($add){
            $this->success('添加成功','reason/index');
        }else{
            $this->error('添加失败');
        }
    }
    public function edit($id)
    {
        $reason=ReasonModel::get($id);
        return $this->fetch('',['reason'=>$reason]);
    }
    public function editPost()
    {
        $data=input();
        if(empty($data['name'])){
            $this->error('原因不能为空');
        }
        $edit=ReasonModel::update($data,['id'=>$data['id']]);
        if ($edit){
            $this->success('修改成功','reason/index');
        }else{
            $this->error('修改失败');
        }
    }

    public function delete()
    {
        $data=input();
        $del=ReasonModel::destroy($data['id']);
        if ($del){
            $this->success('删除成功！','reason/index');
        }else{
            $this->error('删除失败！');
        }
    }
}
